# encoding: utf-8
"""
线程
直接调用 AddThreadTask

AddThreadTask(queryDeployTime, '1111', 'bbb', 'cccc', trunk = 'dddd')

def queryDeployTime(id, name, tt, trunk = None):
    log.info("============== aaaaaaaaaa %s  %s    %s  %s ==============" % (id, name, trunk, tt))

"""
import Queue, threading, traceback
from app.extensions import log
from app import app

THREADPOOL = None


def AddThreadTask(f, *args, **kwargs):
    GetPool().add_task(f, *args, **kwargs)


def GetPool():
    global THREADPOOL
    if THREADPOOL is None:
        THREADPOOL = ThreadPool()
    return THREADPOOL


class Worker(threading.Thread):
    def __init__(self, queue):
        super(Worker, self).__init__()
        self._q = queue
        self.daemon = True
        self.start()

    def run(self):
        while True:
            try:
                f, args, kwargs = self._q.get()
                with app.app_context():
                    f(*args, **kwargs)
            except BaseException:
                log.error(traceback.format_exc())
            self._q.task_done()


class ThreadPool(object):
    def __init__(self, num = 5):
        self._q = Queue.Queue()
        for _ in range(num):
            Worker(self._q)

    def add_task(self, f, *args, **kwargs):
        self._q.put((f, args, kwargs))

    def wait_complete(self):
        self._q.join()
